package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //1. 根据username查询用户信息,如果用户信息不存在,返回错误提示
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("用户不存在");
        }

        //2. 将前台传入的密码进行md5加密,然后跟数据库查询到的密码进行比对,如果失败,返回错误提示
        String md5Password = SecureUtil.md5(password);
        //StringUtils.equals用于对比两个字符串是否相等
        if (!StringUtils.equals(md5Password, employee.getPassword())) {
            return ResultInfo.error("密码错误");
        }

        //3. 查看当前用户状态是否为1,如果不是,表示禁用
        if (employee.getStatus() != 1) {
            return ResultInfo.error("当前用户处于禁用状态,无法登录");
        }

        return ResultInfo.success(employee);
    }

    //根据name查询
    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }

    //保存
    @Override
    public void save(Employee employee) {
        //1.补全参数
        //1-1 id IdUtil.getSnowflake(1,1).nextId()雪花算法 生成唯一数值
        employee.setId(IdUtil.getSnowflake(1, 1).nextId());
        //1-2 密码 [默认值--加密]
        employee.setPassword(SecureUtil.md5("123456"));
        //1-3 状态 [启用]
        employee.setStatus(1);
        //1-4 创建时间和修改时间(默认当前时间)
        //2.调用mapper保存
        employeeMapper.save(employee);
    }

    //根据id查询员工
    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    //修改员工
    @Override
    public void update(Employee employee) {
        //1.补全参数 (设置修改时间和修改人)
        /*employee.setUpdateUser(1L);
        employee.setUpdateTime(new Date());*/
        //2.调用mapper保存
        employeeMapper.update(employee);
    }
}
